package com.example.gitclient.ui;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.gitclient.R;
import com.example.gitclient.adapter.RepositoryAdapter;
import com.example.gitclient.git.GitManager;
import com.example.gitclient.model.Repository;
import com.example.gitclient.utils.RepositoryManager;

import org.eclipse.jgit.api.errors.GitAPIException;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 主界面，显示仓库列表
 */
public class MainActivity extends AppCompatActivity implements RepositoryAdapter.OnRepositoryClickListener {
    private RecyclerView recyclerRepositories;
    private RepositoryManager repositoryManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化仓库管理器
        repositoryManager = new RepositoryManager(this);

        // 初始化视图
        recyclerRepositories = findViewById(R.id.recyclerRepositories);
        recyclerRepositories.setLayoutManager(new LinearLayoutManager(this));

        // 设置按钮点击事件
        Button btnCloneRepository = findViewById(R.id.btnCloneRepository);
        btnCloneRepository.setOnClickListener(v -> showCloneRepositoryDialog());

        Button btnCreateRepository = findViewById(R.id.btnCreateRepository);
        btnCreateRepository.setOnClickListener(v -> showCreateRepositoryDialog());

        // 加载仓库列表
        loadRepositories();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 每次恢复时重新加载仓库列表
        loadRepositories();
    }

    /**
     * 加载仓库列表
     */
    private void loadRepositories() {
        List<Repository> repositories = repositoryManager.getRepositories();
        recyclerRepositories.setAdapter(new RepositoryAdapter(repositories, this));
    }

    /**
     * 显示克隆仓库对话框
     */
    private void showCloneRepositoryDialog() {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_clone_repository, null);
        EditText etRepositoryUrl = dialogView.findViewById(R.id.etRepositoryUrl);
        EditText etRepositoryName = dialogView.findViewById(R.id.etRepositoryName);
        EditText etUsername = dialogView.findViewById(R.id.etUsername);
        EditText etPassword = dialogView.findViewById(R.id.etPassword);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.clone_repository)
                .setView(dialogView)
                .setPositiveButton(R.string.clone, (dialog, which) -> {
                    String url = etRepositoryUrl.getText().toString().trim();
                    String name = etRepositoryName.getText().toString().trim();
                    String username = etUsername.getText().toString().trim();
                    String password = etPassword.getText().toString().trim();

                    if (url.isEmpty() || name.isEmpty()) {
                        Toast.makeText(this, R.string.please_enter_required_fields, Toast.LENGTH_SHORT).show();
                        return;
                    }

                    // 如果用户名或密码为空，则设为null
                    if (username.isEmpty()) username = null;
                    if (password.isEmpty()) password = null;

                    cloneRepository(url, name, username, password);
                })
                .setNegativeButton(R.string.cancel, null)
                .show();
    }

    /**
     * 克隆仓库
     * @param url 远程仓库URL
     * @param name 仓库名称
     * @param username 用户名
     * @param password 密码
     */
    private void cloneRepository(String url, String name, String username, String password) {
        // 创建仓库目录
        File directory = new File(getExternalFilesDir(null), name);
        if (directory.exists()) {
            Toast.makeText(this, R.string.repository_already_exists, Toast.LENGTH_SHORT).show();
            return;
        }

        // 显示进度对话框
        AlertDialog progressDialog = new AlertDialog.Builder(this)
                .setTitle(R.string.cloning_repository)
                .setMessage(R.string.please_wait)
                .setCancelable(false)
                .show();

        // 在后台线程中克隆仓库
        new Thread(() -> {
            try {
                Repository repository = GitManager.cloneRepository(url, directory, username, password);
                repositoryManager.saveRepository(repository);

                // 在UI线程中更新界面
                runOnUiThread(() -> {
                    progressDialog.dismiss();
                    Toast.makeText(this, R.string.repository_cloned_successfully, Toast.LENGTH_SHORT).show();
                    loadRepositories();
                });
            } catch (GitAPIException e) {
                // 在UI线程中显示错误
                runOnUiThread(() -> {
                    progressDialog.dismiss();
                    Toast.makeText(this, getString(R.string.clone_failed) + ": " + e.getMessage(), Toast.LENGTH_LONG).show();
                });
            }
        }).start();
    }

    /**
     * 显示创建仓库对话框
     */
    private void showCreateRepositoryDialog() {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_create_repository, null);
        EditText etRepositoryName = dialogView.findViewById(R.id.etRepositoryName);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.create_repository)
                .setView(dialogView)
                .setPositiveButton(R.string.create, (dialog, which) -> {
                    String name = etRepositoryName.getText().toString().trim();

                    if (name.isEmpty()) {
                        Toast.makeText(this, R.string.please_enter_repository_name, Toast.LENGTH_SHORT).show();
                        return;
                    }

                    createRepository(name);
                })
                .setNegativeButton(R.string.cancel, null)
                .show();
    }

    /**
     * 创建仓库
     * @param name 仓库名称
     */
    private void createRepository(String name) {
        // 创建仓库目录
        File directory = new File(getExternalFilesDir(null), name);
        if (directory.exists()) {
            Toast.makeText(this, R.string.repository_already_exists, Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            Repository repository = GitManager.initRepository(directory);
            repositoryManager.saveRepository(repository);
            Toast.makeText(this, R.string.repository_created_successfully, Toast.LENGTH_SHORT).show();
            loadRepositories();
        } catch (GitAPIException e) {
            Toast.makeText(this, getString(R.string.create_failed) + ": " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onRepositoryClick(Repository repository) {
        // 打开仓库详情界面
        Intent intent = new Intent(this, RepositoryActivity.class);
        intent.putExtra("repository_path", repository.getPath());
        startActivity(intent);
    }
}